package com.shop.web.sso.controller;

import com.shop.Result.LdbzResult;
import com.shop.constant.Const;
import com.shop.pojo.LdbzUser;
import com.shop.sso.api.UserApi;
import com.shop.utils.CookieUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/sso")
public class UserController {

    @Autowired
    private UserApi userApi;

    @Value("${portal_path}")//将常量和配置中的值以及其他的属性值注入到变量中作为初始值
    private String PORTAL_PATH;

    @ResponseBody//将java对象转换为json格式
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(LdbzUser user, String returnUrl, HttpServletResponse response, HttpServletRequest request) {
        LdbzResult result = userApi.login(user);
        if (result.getStatus() == 200){
            //调用setcookie向客户端发送一个HTTP cookie
            CookieUtils.setCookie(request,response, Const.TOKEN_LOGIN,result.getData().toString());
            //有则返回url 跳转
            if (StringUtils.isNotBlank(returnUrl)){
                return "{\"success\":true , \"info\":\"" + returnUrl + "\"}";
            }
            return "{\"success\":true , \"info\":\"" + PORTAL_PATH + "\"}";
            }
            if (result.getStatus()==400){
                return "{\"success\":false , \"info\":\"用户不存在\"}";
            }
            if (result.getStatus()==500){
                return "{\"success\":false , \"info\":\"用户名密码不能为空\"}";
            }

        return  "{\"success\":false , \"info\":\"用户名密码有误\"}";
    }
}
